package com.ld.poetry.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.poetry.config.AppConfigs;
import com.ld.poetry.dao.ResourceConfigMapper;
import com.ld.poetry.entity.ResourceConfig;
import com.ld.poetry.handle.PoetryRuntimeException;
import com.ld.poetry.service.ResourceConfigService;
import com.ld.poetry.utils.DateTimeUtil;
import com.ld.poetry.vo.ResourceConfigUpdateVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class ResourceConfigServiceImpl extends ServiceImpl<ResourceConfigMapper, ResourceConfig> implements ResourceConfigService {
    @Resource
    private AppConfigs appConfigs;


    @Override
    public void initConfig() {
        log.info("init resource config begin.");

        List<ResourceConfig> configList = this.list();

        ResourceConfig config = configList
                .stream()
                .filter(cfg -> Boolean.TRUE.equals(cfg.getSelect()))
                .findAny()
                .orElse(null);
        if(Objects.isNull(config)){
            throw new PoetryRuntimeException("can not found selected resource config.");
        }
        log.info("selected resource config={}",config);
        appConfigs.setSelectedResourceConfig(config);
        appConfigs.setAllResourceConfig(configList);

        log.info("init resource config end.");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSelectConfig(ResourceConfigUpdateVO updateVO) {
        // 将原来的所有配置设置为未选中
        this.update(new LambdaUpdateWrapper<ResourceConfig>()
                .set(ResourceConfig::getSelect,Boolean.FALSE)
                .set(ResourceConfig::getGmtModified, DateTimeUtil.getTimeNow()));

        // 更新当前的配置
        String infoJson = JSON.toJSONString(updateVO.getInfo());
        this.update(new LambdaUpdateWrapper<ResourceConfig>()
                .eq(ResourceConfig::getId,updateVO.getLocalSelectConfigId())
                .set(ResourceConfig::getSelect,Boolean.TRUE)
                .set(ResourceConfig::getInfo,infoJson)
                .set(ResourceConfig::getDownloadUrl,updateVO.getDownloadUrl())
                .set(ResourceConfig::getGmtModified, DateTimeUtil.getTimeNow()));

        // 更新缓存
        this.initConfig();
    }
}
